#include <stdio.h>
#include <iostream>
#include "XmlHeaders.h"
#include "DtdHeaders.h"


using namespace std;

extern FILE* xmlin;
extern FILE* dtdin;
extern int xmlparse(XML **x);
extern int dtdparse(DTD **d);
extern bool check_conformity(const XML *xml,const DTD *dtd);
extern bool matchRegExp(string, string);


// Fr :dans l'execution en ligne de commande il faut specifier en entre le chemin du  fichier xml
// En : you should specify the xml file path while executing inline command
int main(int argc, char **argv)  
{

  if(matchRegExp("toto", "toto"))
	cout<<"Ca match\n";
  else cout<<"Ca match pas\n";

  int err;
  
  DTD* dtd = NULL;
  XML* xml = NULL;
  

  if (argc != 2 )
  {
    cout << "Should be used like this : $ ./analyse rap1.xml" << endl;
    return 0;
  }
  
  //Fr : Recuperation fichier XML
  //En : Getting XML file
  //cout << "im here 1" << endl;
  xmlin = fopen(argv[1], "r");
  if( xmlin == NULL)
  {
    cout << "File : \"" << argv[1] << "\" not found." << endl;
    return 0;
  }
  
cout << "im here 2" << endl;
  //Fr : Verification syntaxique du fichier XML
 //En : checking syntaxically the xml file
  err = xmlparse(&xml);
  cout << "im here 3" << endl;
  if (err != 0)
  {
	  printf("XML File : \"%s\" has %d  syntaxical error(s).\n",argv[1], err);
	  return 0;
  }
  else
  {
	  printf(" XML File: \"%s\"  is syntaxically correct.\n", argv[1]);
  }
  
 
  
  if ( xml->getDTD().empty() )
  {
   cout << "no dtd is referred in the xml file" << endl;
   return 0;
  }
  
  //fr : Recuperation fichier DTD
 //en : getting the dtd file
  string dtd_name = xml->getDTD();
  
  dtdin = fopen(dtd_name.c_str(), "r");
  
  if( dtdin == NULL)
  {
    cout << "the dtd file  : \"" << dtd_name << "\" not found  ." << endl;
    return 0;
  }
  
  //fr : Verification syntaxique du fichier XML
  //en ; checking syntaxically the xml file
  err = dtdparse(&dtd); 
  
  if (err != 0)
  {
	  printf("DTD file  : \"%s\" has %d syntaxical error(s).\n",dtd_name.c_str(), err);
	  return 0;
  }
  else
  {
	  printf("DTD file : \"%s\"  is syntaxically correct.\n", dtd_name.c_str());
	  printf("\n\nChecking validity of the DTD : \n");
	  if (dtd->makeDTD() == -1)
		{
			printf("The DTD is not valid");
			return -1;
		}
	  else printf("The DTD is valid!\n");
	  dtd->display();
  }

  if(check_conformity(xml,dtd)) cout << "xml doc is conform to its dtd "<< endl;
  else cout << "xml doc is not conform to its dtd --> to see errors open the file logErrors.txt "<< endl;
  fclose(xmlin);
  fclose(dtdin); //
  return 0;
}
